import { ref, watch } from 'vue';
import { request } from '@/utils/request';
import { showToast, showLoadingToast, allowMultipleToast } from 'vant';

interface ResDataType {
  message: string;
  result: any;
  status: number;
}
/**
 * 执行请求
 * @param {Function | Object} data
 * @param {Function} success
 * @param {Function} error
 * @returns
 */
export function useRequest(
  data: any,
  success: (res: ResDataType, ...arg: any) => void,
  error?: Function,
  showLoading: boolean = false
) {
  allowMultipleToast(); // 允许多个toast
  const loading = ref(false);

  const execute = (...arg: any[]) => {
    const postData = typeof data === 'function' ? data() : data;
    if (!postData) return; // 参数校验

    loading.value = true;
    const reqFn = postData?.method === 'get' ? request.get : request.post;
    reqFn(postData.url, postData.data, postData.opt)
      .then((res) => {
        if (res.data.status !== 0) {
          const showTip = typeof postData?.opt?.showTip === 'boolean' ? postData?.opt?.showTip : true;
          showTip &&
            showToast({
              message: res.data.message,
              duration: 3000,
            });
          error && error(res);
        } else if (res.status === 0 || res.status === 200) {
          success && success(res.data, ...arg);
        } else {
          console.log('err: ', res);
          error && error(res);
        }
      })
      .catch((err: any) => {
        console.log('err: ', err);
        error && error(err);
      })
      .finally(() => {
        loading.value = false;
      });
  };
  if (showLoading) {
    const loadingToast = ref();
    watch(loading, (v) => {
      if (v) {
        loadingToast.value = showLoadingToast({
          overlay: true,
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0,
        });
      } else {
        loadingToast.value.close();
      }
    });
  }

  return { loading, execute };
}
